package com.zmx.procurementmall.view.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.bumptech.glide.Glide;
import com.lcw.library.imagepicker.ImagePicker;
import com.zmx.procurementmall.BaseActivity;
import com.zmx.procurementmall.MyApplication;
import com.zmx.procurementmall.R;
import com.zmx.procurementmall.fragment.TwoFragment;
import com.zmx.procurementmall.okhttp.OkHttp3ClientManager;
import com.zmx.procurementmall.okhttp.UrlConfig;
import com.zmx.procurementmall.utils.MySharedPreferences;
import com.zmx.procurementmall.view.util.BitmapUtil;
import com.zmx.procurementmall.view.util.GlideLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 程序猿：胖胖祥
 * 时 间：2020/7/22  17:44
 * 功 能：用户资料
 */
public class UserDataActivity extends BaseActivity {

    @BindView(R.id.user_image)
    CircleImageView userImage;
    @BindView(R.id.shop_name)
    TextView shopName;
    @BindView(R.id.layout_shop_name)
    RelativeLayout layoutShopName;
    @BindView(R.id.consignee)
    TextView consignee;
    @BindView(R.id.layout_consignee)
    RelativeLayout layoutConsignee;
    @BindView(R.id.phone)
    TextView phone;
    @BindView(R.id.layout_phone)
    RelativeLayout layoutPhone;
    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.layout_address)
    RelativeLayout layoutAddress;

    private int REQUEST_SELECT_IMAGES_CODE = 1;
    private String imagePath = "";

    private String shop_name,shop_address,shop_consignee,shop_phone;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_user_data;
    }

    @Override
    protected void initViews() {

        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);
        Glide.with(mActivity).load(UrlConfig.IMAGEURL + MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.heading, "")).into(userImage);

        shopName.setText(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.shop_name, ""));
        consignee.setText(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.consignee, ""));
        phone.setText(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.phone, ""));
        address.setText(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.store_address, ""));

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_SELECT_IMAGES_CODE && resultCode == RESULT_OK) {
            List<String> imagePaths = data.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES);

            for (String s : imagePaths) {

                imagePath = s;
                handler.sendEmptyMessage(1);

            }

        }
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {

                case 1:
                    upload();
                    break;
                case 2:

                    Glide.with(mActivity).load(UrlConfig.IMAGEURL + MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.heading, "")).into(userImage);

                    break;

                case 3:
                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Toast(object.getString("message"));
                        if (object.getInt("status") == 200) {

                            shopName.setText(shop_name);
                            MySharedPreferences.getInstance(mActivity).saveKeyObjValue(MySharedPreferences.shop_name,shop_name);

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 4:
                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Toast(object.getString("message"));
                        if (object.getInt("status") == 200) {

                            address.setText(shop_address);
                            MySharedPreferences.getInstance(mActivity).saveKeyObjValue(MySharedPreferences.store_address,shop_address);

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case 5:
                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Toast(object.getString("message"));
                        if (object.getInt("status") == 200) {

                            consignee.setText(shop_consignee);
                            MySharedPreferences.getInstance(mActivity).saveKeyObjValue(MySharedPreferences.consignee,shop_consignee);

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case 6:
                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Toast(object.getString("message"));
                        if (object.getInt("status") == 200) {

                            phone.setText(shop_phone);
                            MySharedPreferences.getInstance(mActivity).saveKeyObjValue(MySharedPreferences.phone,shop_phone);

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
            }
        }
    };


    //上传图片
    private void upload() {

        if (imagePath != null) {

            OkHttpClient okHttpClient = new OkHttpClient();

            MultipartBody.Builder builder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM); //表单上传文件

            File file = new File(new BitmapUtil().compressImage(imagePath)); //根据路径创建file对象
            builder.addFormDataPart("files", //
                    file.getName(),
                    RequestBody.create(MediaType.parse("image/jpeg"), file));

            builder.addFormDataPart("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));

            RequestBody requestBody = builder.build();
            Request request = new Request.Builder()
                    .url(UrlConfig.MODIFYHEAD)
                    .post(requestBody)
                    .build();

            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("onFailure: ", e.toString());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {

                    String Result = response.body().string();

                    Log.e("成功", Result);
                    try {
                        JSONObject object = new JSONObject(Result);

                        if (object.getInt("status") == 200) {

                            //更新头像
                            MySharedPreferences.getInstance(mActivity).saveKeyObjValue(MySharedPreferences.heading, object.getString("imagePath"));
                            handler.sendEmptyMessage(2);

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            });
        }

    }


    @OnClick({R.id.user_image, R.id.layout_shop_name, R.id.layout_consignee, R.id.layout_phone, R.id.layout_address})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.user_image:

                ImagePicker.getInstance()
                        .setTitle("选择图片")//设置标题
                        .showCamera(true)//设置是否显示拍照按钮
                        .showImage(true)//设置是否展示图片
                        .showVideo(false)//设置是否展示视频
                        .setSingleType(true)//设置图片视频不能同时选择
                        .setMaxCount(1)//设置最大选择图片数目(默认为1，单选)
                        .setImageLoader(new GlideLoader())//设置自定义图片加载器
                        .start(mActivity, REQUEST_SELECT_IMAGES_CODE);//REQEST_SELECT_IMAGES_CODE为Intent调用的requestCode

                break;

            case R.id.layout_shop_name:

                final EditText et = new EditText(this);
                new AlertDialog.Builder(this).setTitle("请输入店铺名称")
                        .setView(et)
                        .setPositiveButton("确定", (dialogInterface, i) -> {

                            if (et.getText().toString().equals("")) {

                                Toast("请输入店铺名称");

                            } else {
                                shop_name = et.getText().toString();
                                updateUserShopName(et.getText().toString());

                            }

                        }).setNegativeButton("取消", null).show();


                break;

            case R.id.layout_consignee:

                final EditText et_consignee = new EditText(this);
                new AlertDialog.Builder(this).setTitle("请输入店长名称")
                        .setView(et_consignee)
                        .setPositiveButton("确定", (dialogInterface, i) -> {

                            if (et_consignee.getText().toString().equals("")) {

                                Toast("请输入店长名称");

                            } else {
                                shop_consignee = et_consignee.getText().toString();
                                updateUserConsignee(et_consignee.getText().toString());

                            }

                        }).setNegativeButton("取消", null).show();


                break;

            case R.id.layout_phone:

                final EditText et_phone = new EditText(this);
                new AlertDialog.Builder(this).setTitle("请输入店长电话")
                        .setView(et_phone)
                        .setPositiveButton("确定", (dialogInterface, i) -> {

                            if (et_phone.getText().toString().equals("")) {

                                Toast("请输入店长电话");

                            } else {
                                shop_phone = et_phone.getText().toString();
                                updateUserConsigneePhone(et_phone.getText().toString());

                            }

                        }).setNegativeButton("取消", null).show();



                break;

            case R.id.layout_address:

                final EditText et_address = new EditText(this);
                new AlertDialog.Builder(this).setTitle("请输入店铺地址")
                        .setView(et_address)
                        .setPositiveButton("确定", (dialogInterface, i) -> {

                            if (et_address.getText().toString().equals("")) {

                                Toast("请输入店铺地址");

                            } else {
                                shop_address = et_address.getText().toString();
                                updateUserAddress(et_address.getText().toString());

                            }

                        }).setNegativeButton("取消", null).show();


                break;

        }
    }


    //修改店铺名称
    public void updateUserShopName(String u_shop_name) {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("u_shop_name", u_shop_name);
        params.put("u_id", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));

        OkHttp3ClientManager.getInstance().NetworkRequestMode(UrlConfig.updateUserShopName, params, handler, 3, 404);

    }
    //修改店铺地址
    public void updateUserAddress(String u_store_address) {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("u_store_address", u_store_address);
        params.put("u_id", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));

        OkHttp3ClientManager.getInstance().NetworkRequestMode(UrlConfig.updateUserAddress, params, handler, 4, 404);

    }
    //修改店铺店长
    public void updateUserConsignee(String u_consignee) {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("u_consignee", u_consignee);
        params.put("u_id", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));

        OkHttp3ClientManager.getInstance().NetworkRequestMode(UrlConfig.updateUserConsignee, params, handler, 5, 404);

    }

    //修改店铺店长电话
    public void updateUserConsigneePhone(String u_consignee_phone) {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("u_consignee_phone", u_consignee_phone);
        params.put("u_id", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));

        OkHttp3ClientManager.getInstance().NetworkRequestMode(UrlConfig.updateUserConsigneePhone, params, handler, 6, 404);

    }


}
